package net.itst.schwarzerdaumen;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;

public class WPlan extends ListActivity {

    private Integer plant_id;
    private ListView lvDays = null;
    private Cursor curWPlan = null;
    private SQLiteDatabase db = null;
    private SchwarzerDaumenDatabase database;
    private String[] arrDays;

    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	database = new SchwarzerDaumenDatabase(this);
	db = database.getReadableDatabase();

	setTitle(R.string.cm_Watering);

	Bundle extras = getIntent().getExtras();
	plant_id = (int) extras.getLong("plant_id");

	this.arrDays = new String[] { this.getString(R.string._mon),
		this.getString(R.string._tue), this.getString(R.string._wed),
		this.getString(R.string._thu), this.getString(R.string._fri),
		this.getString(R.string._sat), this.getString(R.string._sun) };
    }

    @Override
    public void onStart() {
	super.onStart();
	showWPlan();
	useCursor();
    }

    @Override
    public void onResume() {
	super.onResume();
    }

    @Override
    public void onDestroy() {
	super.onDestroy();
	curWPlan.close();
	db.close();
    }

    public void showWPlan() {
	curWPlan = db.query(TablePlants.TABLE_NAME, TablePlants.SQL_GET_DAYS,
		TablePlants.ID + "=?", new String[] { plant_id.toString() },
		null, null, null);

	ArrayAdapter<String> dayAdap = new ArrayAdapter<String>(this,
		R.layout.plan_watering, arrDays);

	lvDays = getListView();
	lvDays.setAdapter(dayAdap);
	lvDays.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	lvDays.setItemsCanFocus(false);

    }

    private void useCursor() {
	curWPlan.moveToFirst();
	for (int i = 0; i < 7; i++) {
	    if (curWPlan.getInt(i) == 1) {
		lvDays.setItemChecked(i, true);
	    }
	}
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
	super.onListItemClick(l, v, position, id);

	CheckedTextView textView = (CheckedTextView) v;
	textView.setChecked(!textView.isChecked());

	updateWPlan(position, textView.isChecked());
    }

    private void updateWPlan(int day, boolean checked) {
	ContentValues values = new ContentValues();
	values.put(TablePlants.SQL_GET_DAYS[day], (checked ? 1 : 0));

	String[] whereArgs = { plant_id.toString() };
	String whereClause = TablePlants.ID + "=?";

	db.update(TablePlants.TABLE_NAME, values, whereClause, whereArgs);

	values.clear();
	values.put(TablePlants.WNEXT, checkNewNext());
	db.update(TablePlants.TABLE_NAME, values, whereClause, whereArgs);

    }

    private String checkNewNext() {
	curWPlan.requery();
	curWPlan.moveToFirst();

	String nextWatering = "";

	TimeZone tzLocal = TimeZone.getDefault();
	Locale lcLocal = Locale.getDefault();
	Calendar dtNow = new GregorianCalendar(tzLocal, lcLocal);

	/* We want Monday to be 0 and Sunday to be 6 */
	int today = dtNow.get(GregorianCalendar.DAY_OF_WEEK);
	today -= 2;
	today = (today < 0) ? 6 : today;

	/*
	 * Find all planned days and remap them. Remapping works like this: the
	 * current day (today) gets set to 0, all subsequent days will get
	 * numbered from 1 to 6.
	 */
	int j = 7;
	int remap = 0;
	int newNext = 0;
	int oldNext = 7;
	for (int i = 0; i < 7; i++) {
	    if (curWPlan.getInt(i) == 1) {
		remap = i - today;
		newNext = (remap < 0) ? remap + 7 : remap;
		j = (newNext < oldNext) ? i : j;
		oldNext = (newNext < oldNext) ? newNext : oldNext;
	    }
	}

	/* At least one day is planned. */
	if (j < 7) {
	    Date date = new Date(dtNow.get(GregorianCalendar.YEAR) - 1900,
		    dtNow.get(GregorianCalendar.MONTH), dtNow
			    .get(GregorianCalendar.DAY_OF_MONTH));
	    dtNow.add(GregorianCalendar.DAY_OF_YEAR, oldNext);
	    date = new Date(dtNow.get(GregorianCalendar.YEAR) - 1900, dtNow
		    .get(GregorianCalendar.MONTH), dtNow
		    .get(GregorianCalendar.DAY_OF_MONTH));
	    nextWatering = new SimpleDateFormat("dd.MM.yyyy").format(date
		    .getTime());
	} else {
	    nextWatering = "";
	}

	return nextWatering;

    }
}